//
//  CZMainTabBar.swift
//  SinaWeiBo
//
//  Created by 刘幼寒 on 5/11/16.
//  Copyright © 2016 刘幼寒. All rights reserved.
//

import UIKit

class CZMainTabBar: UITabBar
{
    
    var composeCallBack: (() -> ())?
    
    
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        //计算frame的宽度
        let width = self.frame.width / 5
        var index = 0
        
        for view in subviews
        {
//            print("view:\(view)")
            //找到UITableBarButton,才是按钮，需要修改frame值
            //UITabBarButton是系统隐藏的类，无法调用这个类的方法
            if view.isKindOfClass(NSClassFromString("UITabBarButton")!)
            {
                //能到这里面来说明view是UITabBarButton类型
                view.frame = CGRect(x: width * CGFloat(index), y: 0, width: width, height: self.frame.height)
                
                index++
                if index == 2
                {
                    index++
                }
            }
        }
        //设置加号按钮的位置
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: self.frame.height)
    }
    
    //MARK: - 按钮点击事件
    func composeButtonClick(button: UIButton)
    {
        //最终要modal出控制器，View不能Modal出控制器,只有控制器才能Modal出控制器，当按钮点击的时候要让控制器去做事情
        composeCallBack?()
        
    }
    
    //MARK: - 懒加载
    lazy var composeButton: UIButton = {
        //创建按钮
        let button = UIButton(type: UIButtonType.Custom)
        //设置按钮
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //按钮的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //添加到父控件
        self.addSubview(button)
        //给按钮添加点击事件
        button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
}
